var index;
var index1;
var index2;
var index3;
var index4;
var index5;
var isEdit = false;
$(function(){
  $.ajax({
    type : "get",
    url : "getLoginInfo.do",
    async : false,
    success : function(v) {
      $("#userName").text(v.userId);
      $("#loginUserId").val(v.userId);
      $("#loginUserRoleId").val(v.roleId);
      $("#userId").val(v.id);
      $("#userDept").val(v.userDept);
      var dept = $("#userDept").val();
      var loginUserRoleId = $("#loginUserRoleId").val();
      if(dept != 0 && checkDept(dept) != 1 && loginUserRoleId != -1  && loginUserRoleId != 2 && loginUserRoleId != 4){
        toastrComponent.show("warning", "对不起你没有权限！");
        return;
      }
      initTab("");
      addSignBtnInit();
      searchBtnInit();
      initBigType();
      doBtnInit();
      thClickSelect();
    }
  });

  function thClickSelect() {
    var layData = [ 'form' ];
    layui.use(layData, function() {
      var form = layui.form;
      form.on('select(source)', function(data){
        var thName = $("#source").val();
        if("同行" == thName){
          $("#thDiv").css("display","");
        }else {
          $("#thDiv").css("display","none");
        }
      });
    });

  }

  layui.use(['upload','layer'], function(){
    var upload = layui.upload;
    var layer = layui.layer;
    upload.render({
      elem: '#test2'
      ,url: '/upload.do'
      ,multiple: true
      ,size: 10240 //限制文件大小，单位 KB
      ,accept: 'file'
      ,exts: 'jpg|jpeg|png|bmp|'
      ,number: 5
      ,before: function(obj){
        layer.load(); //上传loading
        var signId = $("#kitSignId").val();
        this.data={'fileTypeId': signId,"fileType":1};
      }
      ,done: function(res){
        console.log(res);
        $("#kitUl").html(getKitHtml(res.data));
        //上传完毕
        layer.closeAll('loading');
      }
    });
  });

  $("#kitUl").on("click",".kitUrl",function(){
    var id = $(this).attr("id");
    window.open("/showImage.do?id=" + id);
  });

  $("#kitUl").on("click",".deleteKit",function(){
    var id = $(this).attr("id");
    var li = $(this).parent();
    swal({
      title: "你确定要删除该附件？",
      type: "warning",
      allowOutsideClick: true,
      showConfirmButton: true,
      showCancelButton: true,
      confirmButtonClass: "layui-btn layui-btn-warm",
      cancelButtonClass: "layui-btn layui-btn-primary",
      confirmButtonText: "确认",
      cancelButtonText: "取消"
    }, function (o) {
      if (o) {
        $.ajax({
          type: "get",
          url: "deleteKit.do",
          data: {
            "id": id
          },
          success: function (data) {
            if (data == "success") {
              li.remove();
              toastrComponent.show("success", "删除成功!");
            }
          }
        });
      }
    });
  });

});


function doBtnInit() {
  $("#signTableDiv").on("click",".stopOver",function () {
    var signId = $(this).attr("signId");
    swal({
      title: "你确定该合同已经终止？",
      type: "warning",
      allowOutsideClick: true,
      showConfirmButton: true,
      showCancelButton: true,
      confirmButtonClass: "layui-btn layui-btn-warm",
      cancelButtonClass: "layui-btn layui-btn-primary",
      confirmButtonText: "确认",
      cancelButtonText: "取消"
    }, function (o) {
      if (o) {
        $.ajax({
          type: "get",
          url: "stopOverSign.do",
          data: {
            "signId": signId,
            "signType": 1
          },
          success: function (data) {
            if (data == "success") {
              tablerelaod("signTab");
              toastrComponent.show("success", "操作成功！");
            }
          }
        });
      }
    });

  });

  $("#signTableDiv").on("click",".kit",function () {
    var signId = $(this).attr("signId");
    $("#kitSignId").val(signId);
    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index5 = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:'附件信息',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen5')//打开的内容
      });
    });

    $.ajax({
      type: "get",
      url: "getKitList.do",
      data: {
        "fileType": 1,
        "fileTypeId": signId
      },
      success: function (data) {
        $("#kitUl").html(getKitHtml(data));
      }
    });

  });
  //申请审批事件
  $("#signTableDiv").on("click",".askApprovalSign",function () {
    var signId = $(this).attr("signId");
    var approvalState = $(this).attr("approvalState");
    swal({
      title: "你确定要发起审批？",
      type: "warning",
      allowOutsideClick: true,
      showConfirmButton: true,
      showCancelButton: true,
      confirmButtonClass: "layui-btn layui-btn-warm",
      cancelButtonClass: "layui-btn layui-btn-primary",
      confirmButtonText: "确认",
      cancelButtonText: "取消"
    }, function (o) {
      if (o) {
        $.ajax({
          type: "get",
          url: "askApproval.do",
          data: {
            "signId": signId,
            "approvalState": approvalState
          },
          success: function (data) {
            if (data == "success") {
              tablerelaod("signTab");
              toastrComponent.show("success", "已提交审批");
            }
          }
        });
      }
    });
  });

  //审批按钮弹框
  $("#signTableDiv").on("click",".approvalSign",function () {
    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index1 = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:'审批签约客户',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen1')//打开的内容
      });
    });

    var signId = $(this).attr("signId");
    var approvalState = $(this).attr("approvalState");

    $("#approvalSignId").val(signId);
    $("#approvalSignState").val(approvalState);
  });

  //审批界面关闭
  $("#cancelApprovalBtn").on("click", function () {
    layer.close(index1);
  });
  //保存审批结果
  $("#saveApproval").on("click",function () {
    var signId = $("#approvalSignId").val();
    var approvalState = $("#approvalSignState").val();
    var approvalResult = $("input[name='approvalResult']:checked").val();
    var approvalAdvice = $("#approvalAdvice").val();
    if(approvalAdvice == ""){
      toastrComponent.show("warning", "请填写审批意见！");
      return;
    }
    $.ajax({
      type: "get",
      url: "doApproval.do",
      data: {
        "signId": signId,
        "approvalState": approvalState,
        "approvalResult":approvalResult,
        "approvalAdvice":approvalAdvice
      },
      success: function (data) {
        if (data == "success") {
          tablerelaod("signTab");
          toastrComponent.show("success", "审批成功");
          $("#approvalAdvice").val("");
          var form = layui.form;
          form.val("approvalForm", {
            "approvalResult": "1"
          })
        }
        layer.close(index1);
      }
    });
  });

  //显示已匹配公司信息
  $("#signTableDiv").on("click",".showMatchedQy",function () {
    var signId = $(this).attr("signId");
    layui.use(['table'], function() {
      var table = layui.table;
      table.render({
        elem: '#matchedQyTab'
        , url: 'getMatchedQyInfo.do?signId=' + signId
        ,page: {
          layout: ['count', 'prev', 'page', 'next', 'skip']
          , groups: 1 //只显示 1 个连续页码
          , first: false //不显示首页
          , last: false //不显示尾页
          , limit: 5
          , limits: [5]
        }
        , cols: [[
          {field: 'qyName', align: 'center', width: '10.9%', title: '名称'}
          ,{field: 'qyPhone', align: 'center', width: '9%', title: '电话'}
          ,{field: 'qyCreateUserName', align: 'center', width: '6%', title: '创建人'}
          ,{field: 'bigType', align: 'center', width: '8%', title: '大类'}
          ,{field: 'smallType', align: 'center', width: '8%', title: '小类'}
          ,{field: 'unit', align: 'center', width: '5%', title: '年限',templet: function (data) {
            var chUnit;
            if(data.unit == 1){
              chUnit="一年";
            }else if(data.unit == 2){
              chUnit="两年";
            }else if(data.unit == 3){
              chUnit="三年";
            }
            return  chUnit;
          }}
          ,{field: 'purpose', align: 'center', width: '5%', title: '用途'}
          ,{field: 'project', align: 'center', width: '7%', title: 'B证'}
          ,{field: 'initStatus', align: 'center', width: '5%', title: '状态'}
          ,{field: 'price', align: 'center', width: '6%', title: '价格'}
          , {field: 'peopleNum', align: 'center', width: '6%',title: '人数'}
          , {field: 'firstPrice', align: 'center', width: '6%', title: '预付款'}
          , {field: 'scendPrice', align: 'center', width: '6%', title: '中期款'}
          , {field: 'thirdPrice', align: 'center', width: '6%', title: '尾款'}
        ]]

      });
    })
    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index5 = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:'已匹配企业信息',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen6')//打开的内容
      });
    });
  });

  //显示审批记录
  $("#signTableDiv").on("click",".showApproval",function () {
    var signId = $(this).attr("signId");
    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index2 = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:'审批记录',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen2')//打开的内容
      });
    });

    $.ajax({
      type: "get",
      url: "getApprovalBySignId.do",
      data: {
        "signId": signId
      },
      success: function (data) {
          var html = "";
          if(data.length == 0){
            html += '<li class="layui-timeline-item"><i class="layui-icon layui-timeline-axis"></i>' +
                '<div class="layui-timeline-content layui-text"><h3 class="layui-timeline-title">无</h3></div></li>'
          }else {
            $.each(data,function (index,item) {
              if(item.approvalResult == "发起审批"){
                html += '<li class="layui-timeline-item"><i class="layui-icon layui-timeline-axis"></i>' +
                    '<div class="layui-timeline-content layui-text"><h3 class="layui-timeline-title">'+item.approvalTime+'</h3><p><span style="">' +
                    item.approvalUserName + '&nbsp;</span>发起了签约客户审批流程' + '<br></p></div></li>'
              }else{
                html += '<li class="layui-timeline-item"><i class="layui-icon layui-timeline-axis"></i>' +
                    '<div class="layui-timeline-content layui-text"><h3 class="layui-timeline-title">'+item.approvalTime+'</h3><p><span style="">' +
                    item.approvalUserName + '&nbsp;</span>审批了你的签约客户申请，审批结果为：' + item.approvalResult +
                    '<br>审批意见：' + item.approvalAdvice
                    + '</p></div></li>'
              }
            })
          }

        $("#approvalList").html(html);

      }
    });

  });

  //编辑签约客户
  $("#signTableDiv").on("click",".editSign",function () {
    $("#actId").css("display","");
    isEdit = true;
    var signId = $(this).attr("signId");
    $("#editSignId").val(signId);
    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:'审批记录',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen')//打开的内容
      });
    });

    $.ajax({
      type: "get",
      url: "getSignById.do",
      data: {
        "signId": signId
      },
      success: function (data) {
        $("#name").val(data.name);
        $("#phone").val(data.phone);
        $("#price").val(data.price);
        $("#mark").val(data.mark);
        $("#thName").val(data.thName);
        if("同行" == data.source){
          $("#thDiv").css("display","");
        }else {
          $("#thDiv").css("display","none");
        }
        $.ajax({
          type: "get",
          url: "getAllSmallType.do?parentId=" + data.bigTypeId,
          success: function (smallData) {
            var smallhtml =  '<option value="">选择或搜索</option>';
            $.each(smallData, function (i, item) {
              smallhtml += '<option value="'+item.id+'">'+item.typeName+'</option>';
            });
            $("#smallType").html(smallhtml);
            var form = layui.form;
            form.val("signForm", {
              "bigType": data.bigTypeId,
              "smallType": data.smallTypeId,
              "purpose": data.purpose,
              "project": data.project,
              "unit": data.unit,
              "initStatus": data.initStatus,
              "source": data.source
            })

          }
        });
      }
    });

  });

  $("#signTableDiv").on("click", ".deleteSign", function () {
    var signId = $(this).attr("signId");
    swal({
      title: "你确定要删除该签约客户？",
      type: "warning",
      allowOutsideClick: true,
      showConfirmButton: true,
      showCancelButton: true,
      confirmButtonClass: "layui-btn layui-btn-warm",
      cancelButtonClass: "layui-btn layui-btn-primary",
      confirmButtonText: "确认",
      cancelButtonText: "取消"
    }, function (o) {
      if (o) {
        $.ajax({
          type: "get",
          url: "deleteSignById.do",
          data: {
            "signId": signId
          },
          success: function (data) {
            if (data == "success") {
              tablerelaod("signTab");
              toastrComponent.show("success", "删除成功");
            }
          }
        });
      }
    });
  });
  $("#signTableDiv").on("click", ".showSign", function () {
    $("#actId").css("display","none");
    var signId = $(this).attr("signId");
    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:'审批记录',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen')//打开的内容
      });
    });

    $.ajax({
      type: "get",
      url: "getSignById.do",
      data: {
        "signId": signId
      },
      success: function (data) {
        $("#name").val(data.name);
        $("#phone").val(data.phone);
        $("#price").val(data.price);
        $("#mark").val(data.mark);
        $("#thName").val(data.thName);
        if("同行" == data.source){
          $("#thDiv").css("display","");
        }else {
          $("#thDiv").css("display","none");
        }
        $.ajax({
          type: "get",
          url: "getAllSmallType.do?parentId=" + data.bigTypeId,
          success: function (smallData) {
            var smallhtml =  '<option value="">选择或搜索</option>';
            $.each(smallData, function (i, item) {
              smallhtml += '<option value="'+item.id+'">'+item.typeName+'</option>';
            });
            $("#smallType").html(smallhtml);
            var form = layui.form;
            form.val("signForm", {
              "bigType": data.bigTypeId,
              "smallType": data.smallTypeId,
              "purpose": data.purpose,
              "project": data.project,
              "initStatus": data.initStatus,
              "source": data.source
            })
          }
        });
      }
    });

  });

  //报销表格初始化
  $("#signTableDiv").on("click",".expend",function () {
    var signId = $(this).attr("signId");
    $("#expendSignId").val(signId);
    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index3 = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:'报销记录',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen3')//打开的内容
      });
    });
    layui.use(['table'], function() {
      var table = layui.table;
      table.render({
        elem: '#expendTab'
        , url: 'getExpend.do?signId=' + signId
        , height: '290',
        page: {
          layout: ['count', 'prev', 'page', 'next', 'skip']
          , groups: 1 //只显示 1 个连续页码
          , first: false //不显示首页
          , last: false //不显示尾页
          , limit: 5
          , limits: [5]
        }
        , cols: [[
          {field: 'expendType', align: 'center', width: '20%', title: '报销类型'}
          ,{field: 'expendPrice', align: 'center', width: '20%', title: '报销金额'}
          , {field: 'expendMark', align: 'center', width: '40%',title: '备注'}
          , {
            field: 'id', align: 'center', width: '20%', title: '操作',
            templet: function (data) {
              var html = '';
              if(data.expendStatus == 4){
                html += '<a class="layui-btn layui-btn-xs" lay-event="edit" style="background-color: #1E9FFF;">审批完成</a>';
              }else if(data.expendStatus == 0){
                html += '<a class="layui-btn layui-btn-xs" lay-event="edit" style="background-color: #FF5722;">审批不通过</a>';
                html += '<a class="layui-btn layui-btn-xs deleteExpendBtn" lay-event="edit" expendId='+data.id+'>删除</a>';
              }else {
                html += '<a class="layui-btn layui-btn-xs" lay-event="edit" >审批中</a>';
              }
              return html;
            }
          }
        ]]
      });
    });
    getExpendTotal(signId);
  });

  //转回款列表
  $("#signTableDiv").on("click",".tpapply",function () {
    var signId = $(this).attr("signId");
    var signType = $(this).attr("signType");
    $("#applySignId").val(signId);
    var type;
    if(signType == 1){
      type="转款";
      $("#applyTypeId").val(1);
    }else {
      type="回款";
      $("#applyTypeId").val(2);
    }

    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index4 = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:type + '记录',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen4')//打开的内容
      });
    });
    layui.use(['table'], function() {
      var table = layui.table;
      table.render({
        elem: '#applyTab'
        , url: 'getApply.do?signId=' + signId
        , height: '290',
        page: {
          layout: ['count', 'prev', 'page', 'next', 'skip']
          , groups: 1 //只显示 1 个连续页码
          , first: false //不显示首页
          , last: false //不显示尾页
          , limit: 5
          , limits: [5]
        }
        , cols: [[
          {field: 'applyType', align: 'center', width: '20%', title: type + '类型'}
          ,{field: 'applyPrice', align: 'center', width: '20%', title: '金额'}
          , {field: 'applyMark', align: 'center', width: '30%',title: '备注'}
          , {
            field: 'applyTypeId', align: 'center', width: '10%', title: '操作类型',
            templet: function (data) {
             if(data.applyTypeId == 1){
               return "转款";
             }else if(data.applyTypeId == 2){
               return "回款";
             }else {
               return "";
             }
            }
          }
          , {
            field: 'id', align: 'center', width: '20.3%', title: '状态',
            templet: function (data) {
              var html = '';
              if(data.applyState == 5){
                html += '<a class="layui-btn layui-btn-xs" lay-event="edit" style="background-color: #1E9FFF;">审批完成</a>';
              }else if(data.applyState == 0){
                html += '<a class="layui-btn layui-btn-xs" lay-event="edit" style="background-color: #FF5722;">审批不通过</a>';
              }else {
                html += '<a class="layui-btn layui-btn-xs" lay-event="edit" >审批中</a>';
              }
              return html;
            }
          }
        ]]
      });
    });
    getApplyTotal(signId);
  });

  $("#addExpendBtn").on("click",function () {
    var expendType = $("#expendType").val();
    var expendPrice = $("#expendPrice").val();
    var expendMark = $("#expendMark").val();
    var signId = $("#expendSignId").val();
    if("" == expendType){
      toastrComponent.show("warning", "请选择报销类型！");
      return;
    }
    if("" == expendPrice){
      toastrComponent.show("warning", "请填写报销金额！");
      return;
    }
    var reg = /^[0-9]+([.]{1}[0-9]{1,2})?$/;
    if(!reg.test(expendPrice)){
      toastrComponent.show("warning", "报销金额不合法！");
      return;
    }

    if("" == expendMark){
      toastrComponent.show("warning", "填写报销备注！");
      return;
    }
    if(expendMark.length > 255){
      toastrComponent.show("warning", "报销备注最多255个字符！");
      return;
    }
    $.ajax({
      type: "get",
      url: "addExpendInfo.do",
      data: {
        "expendType": expendType,
        "expendPrice": expendPrice,
        "expendMark": expendMark,
        "signId": signId
      },
      success: function (data) {
        if (data == "success") {
          tablerelaod("expendTab");
          toastrComponent.show("success", "添加成功");
          $("#expendPrice").val("");
          $("#expendMark").val("");
          var form = layui.form;
          form.val("expendForm", {
            "expendType": ""
          });
          getExpendTotal(signId);
        }
      }
    });
  });
  $("#addApplyBtn").on("click",function () {
    var applyType = $("#applyType").val();
    var applyPrice = $("#applyPrice").val();
    var applyMark = $("#applyMark").val();
    var signId = $("#applySignId").val();
    var applyTypeId = $("#applyTypeId").val();
    var type;
    if(applyTypeId == 1){
      type="转款";
      $("#applyTypeId").val(1);
    }else {
      type="回款";
      $("#applyTypeId").val(2);
    }
    if("" == applyType){
      toastrComponent.show("warning", "请选择类型！");
      return;
    }
    if("" == applyPrice){
      toastrComponent.show("warning", "请填写金额！");
      return;
    }
    var reg = /^[0-9]+([.]{1}[0-9]{1,2})?$/;
    if(!reg.test(applyPrice)){
      toastrComponent.show("warning", "金额不合法！");
      return;
    }

    if("" == applyMark){
      toastrComponent.show("warning", "填写备注！");
      return;
    }
    if(applyMark.length > 255){
      toastrComponent.show("warning", "备注最多255个字符！");
      return;
    }
    swal({
      title: "你确定要提交该"+type+"申请？",
      type: "warning",
      allowOutsideClick: true,
      showConfirmButton: true,
      showCancelButton: true,
      confirmButtonClass: "layui-btn layui-btn-warm",
      cancelButtonClass: "layui-btn layui-btn-primary",
      confirmButtonText: "确认",
      cancelButtonText: "取消"
    }, function (o) {
      if (o) {
        $.ajax({
          type: "get",
          url: "addApplyInfo.do",
          data: {
            "applyType": applyType,
            "applyPrice": applyPrice,
            "applyMark": applyMark,
            "applyTypeId": applyTypeId,
            "signId": signId
          },
          success: function (data) {
            if (data == "success") {
              tablerelaod("applyTab");
              toastrComponent.show("success", "添加成功");
              $("#applyPrice").val("");
              $("#applyMark").val("");
              var form = layui.form;
              form.val("applyForm", {
                "applyType": ""
              });
              //getApplyTotal(signId);
            }
          }
        });
      }
    });

  });

  $("#expendTabDiv").on("click",".deleteExpendBtn",function () {
    var expendId = $(this).attr("expendId");
    swal({
      title: "你确定要删除该笔报销？",
      type: "warning",
      allowOutsideClick: true,
      showConfirmButton: true,
      showCancelButton: true,
      confirmButtonClass: "layui-btn layui-btn-warm",
      cancelButtonClass: "layui-btn layui-btn-primary",
      confirmButtonText: "确认",
      cancelButtonText: "取消"
    }, function (o) {
      if (o) {
        $.ajax({
          type: "get",
          url: "deleteExpend.do",
          data: {
            "expendId": expendId
          },
          success: function (data) {
            if (data == "success") {
              tablerelaod("expendTab");
              toastrComponent.show("success", "删除成功");
              getExpendTotal($("#expendSignId").val());
            }
          }
        });
      }
    });
  });

}

function getExpendTotal(signId) {
  $.ajax({
    type: "get",
    url: "getAllExpend.do",
    data: {
      "signId": signId
    },
    success: function (data) {
      if("" == data){
        $("#expendTotal").text("0");
      }else {
        $("#expendTotal").text(data);
      }
    }
  });
}

function getApplyTotal(signId) {
  $.ajax({
    type: "get",
    url: "getAllApply.do",
    data: {
      "signId": signId
    },
    success: function (data) {
      if("" == data){
        $("#applyTotal").text("0");
      }else {
        $("#applyTotal").text(data);
      }
    }
  });
}

//初始化大类小类
function initBigType() {
  $.ajax({
    type: "get",
    url: "getAllBigType.do",
    success: function (data) {
      var html =  '<option value="">选择或搜索</option>';
      $.each(data, function (i, item) {
        html += '<option value="'+item.id+'">'+item.typeName+'</option>';
      });
      $("#bigType").html(html);

      layui.use(['form'], function () {
        var form = layui.form;
        form.on('select(bigType)', function(data){
          $.ajax({
            type: "get",
            url: "getAllSmallType.do?parentId=" + data.value,
            success: function (smallData) {
              var smallhtml =  '<option value="">选择或搜索</option>';
              $.each(smallData, function (i, item) {
                smallhtml += '<option value="'+item.id+'">'+item.typeName+'</option>';
              });
              $("#smallType").html(smallhtml);

              form.render('select');
            }
          });
        });
      });
    }
  });
}


//搜索按钮事件
function searchBtnInit() {
	$("#searchBtn").on("click",function () {
		var serachStr = $("#searchStr").val();
    initTab(serachStr);
  });
}
//添加签约客户按钮弹框
function addSignBtnInit() {
	$("#addSignBtn").on("click",function () {
    $("#actId").css("display","");
    isEdit = false;
    setNull();
    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index = layer.open({
        type:1,//类型
				area: ['auto', 'auto'],//定义宽和高
        title:'添加签约客户',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen')//打开的内容
      });
    });

    $("#name").focus();
  });

	//添加签约客户关闭按钮事件
  $("#cancelBtn").on("click", function () {
    layer.close(index);
  });

  //保存签约客户按钮事件
  $("#saveSignBtn").on("click",function () {
		var name = $("#name").val();
		var phone = $("#phone").val();
		var bigType = $("#bigType").val();
		var smallType = $("#smallType").val();
		var purpose = $("#purpose").val();
		var project = $("#project").val();
		var initStatus = $("#initStatus").val();
		var price = $("#price").val();
		var unit = $("#unit").val();
		var mark = $("#mark").val();
		var source = $("#source").val();
		var thName = $("#thName").val();

    if("" == name){
      toastrComponent.show("warning", "请填写名称！");
      return;
    }
    if(name.length > 50){
      toastrComponent.show("warning", "名称最多50个字符！");
      return;
    }
    if("" == phone){
      toastrComponent.show("warning", "请填写电话！");
      return;
    }
    var reg = /^[0-9]*$/;
    if(!reg.test(phone) || phone.length > 12){
      toastrComponent.show("warning", "请填写合法的电话号码！");
      return;
    }
    if("" == source){
      toastrComponent.show("warning", "请选择客户来源！");
      return;
    }

    if("" == bigType){
      toastrComponent.show("warning", "请选择大类！");
      return;
    }
    if("" == smallType){
      toastrComponent.show("warning", "请选择小类！");
      return;
    }
    if("" == price){
      toastrComponent.show("warning", "请填写价格！");
      return;
    }
    var reg1 = /^[0-9]+([.]{1}[0-9]+){0,1}$/;
    if(!reg1.test(price)){
      toastrComponent.show("warning", "请填写合法的价格！");
      return;
    }
    if("" == unit){
      toastrComponent.show("warning", "请选择年限！");
      return;
    }
    if("" == purpose){
      toastrComponent.show("warning", "请选择用途！");
      return;
    }
    if("" == project){
      toastrComponent.show("warning", "请选择项目！");
      return;
    }
    if("" == initStatus){
      toastrComponent.show("warning", "请选择状态！");
      return;
    }

    if("同行" == source && "" == thName){
      toastrComponent.show("warning", "请填写同行公司名称！");
      return;
    }

    if("同行" == source && thName.length > 100 ){
      toastrComponent.show("warning", "同行公司名称最多100个字符！！");
      return;
    }

    if(mark.length > 255){
      toastrComponent.show("warning", "备注最多255个字符！");
      return;
    }

    var url = "saveSign.do";
    var signId = $("#editSignId").val();
    if(isEdit){
      url = "editSign.do";
    }

    $.ajax({
      type: "get",
      url: url,
      data: {
        "name": name,
        "phone": phone,
        "bigType": bigType,
        "smallType": smallType,
        "purpose": purpose,
        "initStatus": initStatus,
        "project": project,
        "price": price,
        "unit": unit,
        "mark": mark,
        "source": source,
        "thName": thName,
        "signType": 1,
        "signId":signId
      },
      success: function (data) {
      	if("success" == data){
          toastrComponent.show("success", "保存成功！");
          layer.close(index);
          $("#searchStr").val("");
          initTab("");
          setNull();
				}
      }
    });
  });
}

function setNull() {
  $("#name").val("");
  $("#phone").val("");
  $("#price").val("");
  $("#mark").val("");
  $("#thName").val("");
  $("#smallType").html("");
  var form = layui.form;
  form.val("signForm", {
    "purpose": ""
    ,"bigType": ""
    ,"smallType": ""
    ,"project": ""
    ,"initStatus": ""
    ,"unit": ""
    ,"source": ""
  })
}

//初始化表格
function initTab(search) {
  layui.use(['table'], function() {
    var table = layui.table;
    table.render({
      elem: '#signTab'
      , url: 'getSignCustom.do?signType=1&search=' + search
      , height: '480',
      page: {
        layout: ['count', 'prev', 'page', 'next', 'skip']
        , groups: 1 //只显示 1 个连续页码
        , first: false //不显示首页
        , last: false //不显示尾页
        , limit: 10
        , limits: [10]
      }
      , cols: [[
        {field: 'name', align: 'center', width: '9%', title: '名称'}
        ,{field: 'phone', align: 'center', width: '9%', title: '电话'}
        , {field: 'bigType', align: 'center', width: '8%',title: '大类'}
        , {field: 'smallType', align: 'center', width: '8%', title: '小类'}
        // , {field: 'purpose', align: 'center', width: '5%', title: '用途'}
        // , {field: 'project', align: 'center', width: '5%', title: 'B证'}
        // , {field: 'initStatus', align: 'center', width: '5%', title: '状态'}
        , {field: 'price', align: 'center', width: '6%', title: '价格'}
        , {field: 'unit', align: 'center', width: '5%', title: '年限',templet: function (data) {
          var chUnit;
          if(data.unit == 1){
            chUnit="一年";
          }else if(data.unit == 2){
            chUnit="两年";
          }else if(data.unit == 3){
            chUnit="三年";
          }
          return  chUnit;
        }}
        , {field: 'source', align: 'center', width: '7%', title: '来源'}
        , {field: 'thName', align: 'center', width: '7%', title: '同行公司'}
        , {field: 'createUserName', align: 'center', width: '6%', title: '录入人'}
        , {field: 'expense', align: 'center', width: '7%', title: '费用报销',
          templet: function (data) {
            var html = '<a class="layui-btn layui-btn-xs expend" lay-event="edit" signId='+data.id+' >费用报销</a>';
            return html;
          }}
        , {field: 'createTime', align: 'center', width: '8%', title: '时间'}
        , {field: 'kit', align: 'center', width: '7%', title: '附件信息',
          templet: function (data) {
            var html = '<a class="layui-btn layui-btn-xs kit" lay-event="edit" signId='+data.id+' >附件信息</a>';
            return html;
          }}
        , {field: 'id', align: 'left', width: '13.5%', title: '操作',
          templet: function (data) {
            var html = '';
            var loginUserRoleId = $("#loginUserRoleId").val();
            var loginUserId = $("#userId").val();
            if(data.approvalState == 0 && data.createUserId == loginUserId){
              html += '<a class="layui-btn layui-btn-xs editSign" lay-event="edit" signId='+data.id+' approvalState='+data.approvalState+'>编辑</a>';
              html += '<a class="layui-btn layui-btn-xs deleteSign" lay-event="edit" signId='+data.id+' approvalState='+data.approvalState+'>删除</a>';
              html += '<a class="layui-btn layui-btn-xs askApprovalSign" lay-event="edit" signId='+data.id+' approvalState='+data.approvalState+'>申请审批</a>';
            }else{
              if(data.approvalState == loginUserRoleId && loginUserRoleId <=3){
                html += '<a class="layui-btn layui-btn-xs approvalSign" lay-event="edit" style="background-color: #1E9FFF;" signId='+data.id+' approvalState='+data.approvalState+'>审批</a>';
                html += '<a class="layui-btn layui-btn-xs showApproval" lay-event="edit" signId='+data.id+' approvalState='+data.approvalState+'>审批记录</a>';
              }else {
                  if(data.approvalState == 4){
                    if(data.stopOver == 1){
                      html += '<a class="layui-btn layui-btn-xs" style="background-color: #FFB800;" lay-event="edit" signId='+data.id+' approvalState='+data.approvalState+'>合同终止</a>';
                    }else {
                      html += '<a class="layui-btn layui-btn-xs showMatchedQy" style="background-color: #FF5722;" lay-event="edit" signId='+data.id+' approvalState='+data.approvalState+'>审批完成</a>';
                      if(data.createUserId == loginUserId){
                        if(data.signType == 1){
                          html += '<a class="layui-btn layui-btn-xs tpapply" lay-event="edit" signId='+data.id+' signType='+data.signType+'>申请转款</a>';
                        }else {
                          html += '<a class="layui-btn layui-btn-xs tpapply" lay-event="edit" signId='+data.id+' signType='+data.signType+'>申请回款</a>';
                        }
                      }else if(loginUserRoleId == 3){
                        html += '<a class="layui-btn layui-btn-xs stopOver" style="background-color: red;" lay-event="edit" signId='+data.id+'>终止</a>';
                      }else if(loginUserRoleId == -1){
                        html += '<a class="layui-btn layui-btn-xs editSign" lay-event="edit" signId='+data.id+' approvalState='+data.approvalState+'>编辑</a>';
                      }else if(loginUserRoleId == 7){
                        if(data.matchSign == 0){
                          html += '<a class="layui-btn layui-btn-xs showMatchedQy" style="background-color: green;" lay-event="edit" signId='+data.id+' approvalState='+data.approvalState+'>未匹配</a>';
                        }else {
                          html += '<a class="layui-btn layui-btn-xs showMatchedQy" style="background-color: red;" lay-event="edit" signId='+data.id+' approvalState='+data.approvalState+'>已匹配</a>';
                        }

                      }
                    }
                  }else{
                    html += '<a class="layui-btn layui-btn-xs showApproval" lay-event="edit" signId='+data.id+' approvalState='+data.approvalState+'>审批记录</a>';
                  }
              }
              html += '<a class="layui-btn layui-btn-xs showSign" lay-event="edit" signId='+data.id+' approvalState='+data.approvalState+'>查看</a>';
            }
            return html;
          }
        }
      ]]
    });
  })
}


function tablerelaod(tableId) {
  var table = layui.table;
  table.reload(tableId);
}